import io
import os
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

from Alpaca.settings import EMAIL_SEND_USERNAME, EMAIL_SEND_PASSWORD, EMAIL_SEND_FROM


def send_email_reports(receiver, report_name, html_report_path, runner=None):
    if '@sina.com' in EMAIL_SEND_USERNAME:
        smtp_server = 'smtp.sina.com'
    elif '@163.com' in EMAIL_SEND_USERNAME:
        smtp_server = 'smtp.163.com'
    else:
        smtp_server = 'smtp.exmail.qq.com'

    if runner:
        successes = runner.summary.get('stat').get('successes')
        testsRun = runner.summary.get('stat').get('testsRun')
    else:
        successes = 5
        testsRun = 10

    percent = int(successes) / int(testsRun) * 100
    percent = '%.2f' % percent
    subject = "【" + report_name + "UI自动化测试报告" + "】 - 成功率：" + str(percent) + "%"

    with io.open(html_report_path, 'r', encoding='utf-8') as stream:
        send_file = stream.read()

    # 附件
    att = MIMEText(send_file, "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = "attachment;filename = TestReport.html"

    # 图片
    pic_path = os.getcwd() + '/static/viewfile.png'
    img = MIMEImage(open(pic_path, 'rb').read())
    img.add_header('Content-ID', '<image1>')

    html_report_path = html_report_path.split('/')[-1]
    # 正文
    body = MIMEText('<html><body><p>Hi,all</p>'
                    '<p>以下北京自动化测试团队%s测试报告概要</p>'
                    '<p>本次运行测试用例总数：%s, 成功数量：%s</p>'
                    '<p>查看详细内容请点击：<a href="http://20.1.1.210:9000/ui/view_report/?report_path=%s">报告详情</a></p>'
                    '<p>如有疑问，请咨询北京自动化测试团队：<a>autotest@weshare.com.cn</a></p>'
                    '<p><img src="cid:image1"></p>'
                    '</body></html>' % (report_name, str(testsRun), str(successes), html_report_path), 'html', 'utf-8')

    msg = MIMEMultipart('related')
    msg['Subject'] = subject
    msg['From'] = EMAIL_SEND_USERNAME
    msg['to'] = receiver
    # msg.attach(att)
    msg.attach(body)
    msg.attach(img)

    smtp = smtplib.SMTP()
    smtp.connect(smtp_server)
    smtp.starttls()
    smtp.login(EMAIL_SEND_USERNAME, EMAIL_SEND_PASSWORD)
    smtp.sendmail(EMAIL_SEND_USERNAME, receiver.split(','), msg.as_string())
    smtp.quit()


if __name__ == '__main__':
    # send_email_reports('##@qq.com, example@163.com', 'D:\\HttpRunnerManager\\reports\\2018-06-05 15-58-00.html')
    send_email_reports('yuanweixin@weshare.com.cn', 'test',
                       '/home/bj-x250-w/Documents/git/intest/Alpaca/templates/reports/演示用/演示用-2018-10-08 15:27:48.html')
